﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharp.Study.Test
{
    public class Utils
    {
        public static bool ObjToBoolPython(object obj)
        {
            if (obj == null)
            {
                return false;
            }

            if (obj is byte)
            {
                return (byte)obj != 0;
            }

            if (obj is bool)
            {
                return (bool)obj;
            }

            if (obj is int)
            {
                return (int)obj != 0;
            }

            if (obj is long)
            {
                return (long)obj != 0;
            }

            if (obj is float)
            {
                return (float)obj != 0f;
            }

            if (obj is decimal)
            {
                return (decimal)obj != 0m;
            }

            if (obj is double)
            {
                return (double)obj != 0.0;
            }

            if (obj is string)
            {
                string text = obj.ToString()!.ToLower();
                if (string.IsNullOrEmpty(text))
                {
                    return false;
                }

                if (text == "true")
                {
                    return true;
                }

                if (text == "false")
                {
                    return false;
                }

                double result = 0.0;
                if (!double.TryParse(text, out result))
                {
                    return true;
                }

                return result != 0.0;
            }

            if (obj is Array)
            {
                return ((Array)obj).Length != 0;
            }

            return true;
        }

    }
}
